﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KCL.Code.Entities;
using KCL.Code.Business;
using KCL.Code.Data;
using Newtonsoft.Json;

namespace KCL.Management
{
    /// <summary>
    /// Summary description for PhaseManagement
    /// </summary>
	public class OrderHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // get parameters from query string
			Order order = null;
			int payMethodType = context.Request.Form["payMethodType"] != null ? Convert.ToInt32(context.Request.Form["payMethodType"]) : 0;
			int payMethodAmount = context.Request.Form["payMethodAmount"] != null ? Convert.ToInt32(context.Request.Form["payMethodAmount"]) : 0;
			var action = context.Request.Form["action"] != null ? context.Request.Form["action"].Trim().Replace("'", "''") : "";
			string code = "";
			
            context.Response.ContentType = "application/html";
			try
			{
				order = (Order)JsonConvert.DeserializeObject(context.Request.Form["order"], typeof(Order));
			}
			catch (Exception ex)
			{
				context.Response.Write(string.Format("alert(\"Có lỗi: {0}\");", ex.Message.Replace("\r\n", "\\n").Replace("\"", "'")));
				return;
			}
            // return empty if question or keyword is missing
			if (order.customerId == -1 || order.orderMaterials.Count == 0)
            {
                context.Response.Write("alert(\"Chưa chọn khách hàng hoặc nguyên liệu!\");");
                return;
            }
			
            try
            {
				OrderDAO orderDAO = new OrderDAO();
				order.payMethodId = orderDAO.GetPayMethodId(payMethodType, payMethodAmount);
				if (action == "create")
					code = orderDAO.CreateOrder(order);
				//else if (action == "edit")
				//    PhaseServices.UpdatePhase(phase);
            }
            catch (Exception ex)
            {
				context.Response.Write(string.Format("alert(\"Có lỗi: {0}\");", ex.Message.Replace("\r\n", "\\n")));
                return;
            }

            if (action == "create")
                context.Response.Write(string.Format("alert('Thêm mới thành công.\\nMã đơn hàng là {0}'); self.location='OrderManagement.aspx';", code));
            else if (action == "edit")
                context.Response.Write(string.Format("$('#divCreateUser').dialog('close'); alert('Chỉnh sửa thành công.'); RefreshCustomer({0});", 1));
            else if (action == "delete")
                context.Response.Write("alert('Xóa thành công.');");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}